<?php
/**
 * Created by PhpStorm.
 * User: LYQ
 * Date: 2020/4/1
 * Time: 15:07
 */

namespace app\api\model;


class RedisManagerModel
{
    static private $instances = array();
    /**
     * 实例化redis
     * @param type $adapter
     * @return \Redis
     * @throws \Exception
     */
    static private function createInstance($adapter)
    {
        $config = config('REDIS_LIST');
        $redis = new \Redis();
        if ($config[$adapter]["master"]["persistent"]) {
            $redis->pconnect($config[$adapter]["master"]["host"], $config[$adapter]["master"]["port"]);
            $result = $redis->auth($config[$adapter]["master"]["password"]);
        } else {
            $redis->connect($config[$adapter]["master"]["host"], $config[$adapter]["master"]["port"]);
            $result = $redis->auth($config[$adapter]["master"]["password"]);
        }
        //stanby  进程
        if (!$result) {
            if ($config[$adapter]["standby"]["persistent"]) {
                $redis->pconnect($config[$adapter]["standby"]["host"], $config[$adapter]["standby"]["port"]);
                $result = $redis->auth($config[$adapter]["standby"]["password"]);
            } else {
                $redis->connect($config[$adapter]["standby"]["host"], $config[$adapter]["standby"]["port"]);
                $result = $redis->auth($config[$adapter]["standby"]["password"]);
            }
        }
        if (!$result) {
            throw new \Exception('Redis Connection Error');
        }
        return $redis;
    }

    /**单例模式静态访问该方法
     * @param string $adapter
     * @return Redis
     */
    static public function getInstance($adapter = "db01")
    {
        if (!isset(self::$instances[$adapter])) {
            self::$instances[$adapter] = self::createInstance($adapter);
        }
        return self::$instances[$adapter];
    }
}